<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
    :on-progress="progress"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-show="flag" type="circle" :percentage="percent" />
  </el-upload>
</template>
<script>
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDd7MQMxSjmnaDfuytfKmzweDe7Sv9LM9n', // 身份识别ID
  SecretKey: 'hFftvjXHoaEfv3yd5KVXPDoFZkleOyPd' // 身份秘钥
})
export default {

  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      percent: 0,
      flag: false
    }
  },
  watch: {
    value() {
      this.imageUrl = this.value
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    upload(res) {
      console.log(res)
      this.flag = true
      cos.putObject({

        Bucket: 'wangshuaida-1313015981', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: res.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: res.file, // 上传文件对象
        onProgress: (progressData) => {
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err, data)
        this.flag = false
        this.imageUrl = `https://${data.Location}`
        this.$emit('input', `https://${data.Location}`)
      })
    },
    progress(event, file, fileList) {
      console.log(event, file, fileList)
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    position: relative;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-progress{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }
</style>

